package com.gomefinance.hl.elasticjob.util;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @Author hzj
 * @Date 2017/8/23 17:10
 * @Description :
 */
@Slf4j
public class YmlUtils {
    private LinkedHashMap obj;

    public static class YmlProperties {
        private static final YmlUtils ymlUtils = new YmlUtils();
    }

    public static YmlUtils getInstance() {
        return YmlProperties.ymlUtils;
    }

    private YmlUtils() {
        init();
    }

    /**
     *
     * java读取yml文件后是以 linkedHashMap 的数据接口进行储存的
     *
     */
    private void init() {
        try {
            Yaml yaml = new Yaml();
            URL url = YmlUtils.class.getClassLoader().getResource("config/application.yml");
//            File file = new File("config/application.yml");
            FileInputStream fileInputStream = new FileInputStream(url.getFile());
            //获取test.yaml文件中的配置数据，然后转换为obj，
            obj = (LinkedHashMap) yaml.load(fileInputStream);
//            log.info("初始化读取配置信息为(obj)：{}",obj.);
            //也可以将值转换为Map
            HashMap map = (HashMap) yaml.load(fileInputStream);
            log.info("初始化读取配置信息为(map)：{}", map);
            //通过map我们取值就可以了.

        } catch (Exception e) {
            log.error("读取配置文件异常", e);
        }

    }

    /**
     * 获取对应key的值
     *
     * @param key
     * @return
     */
    public Object getPropertics(String key) {
        //去除key值中包含的空格字符
        key = key.trim();
        String[] keys = key.split("\\.");

        if (keys.length == 0) return null;

        LinkedHashMap linkedHashMap = obj;
        for (int i = 0; i < keys.length - 1; i++) {
            linkedHashMap = (LinkedHashMap) linkedHashMap.get(keys[i]);
        }
        return linkedHashMap.get(keys[keys.length - 1]);
    }
}
